﻿using MES.Core;
using MES.Core.Model;
using MES.Service;
using MES.Service.Generate;
using Microsoft.AspNetCore.Mvc;
using System.Text.RegularExpressions;

namespace MES.API.Controllers
{
    /// <summary>
    /// 数据库连接池管理
    /// </summary>
    [Route("api/[controller]/[Action]")]
    [ApiController]
    public class LibraryManagerController : ControllerBase
    {
        private readonly LibraryManagerService _libraryManagerService;
        private readonly IGenerateService _generateService;
        public LibraryManagerController(IGenerateService generateService)
        {
            _libraryManagerService = new LibraryManagerService();
            _generateService = generateService;
        }

        /// <summary>
        /// 添加数据库连接池
        /// </summary>
        /// <param name="connectionPool"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<OperateResult> AddConnectionPool([FromBody] ConnectionPool connectionPool)
        {
            if (Regex.IsMatch(connectionPool.DatabaseName, @"[\u4e00-\u9fa5]"))
            {
                return OperateResult.Fail("数据库名称不能包含中文");
            }
            var data = await _libraryManagerService.AddLibraryManager(connectionPool);

            if (data)
            {
                return OperateResult.Success("添加成功");
            }
            else
            {
                return OperateResult.Fail("添加失败");
            }

        }


        /// <summary>
        /// 创建数据库表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<OperateResult> CreateTable(int DatabaseNameid)
        {
            await _generateService.HotLoading();//热加载

            ConnectionPool connectionPool = await _libraryManagerService.GetConnectionPoolAsync(DatabaseNameid);
            if (connectionPool == null)
            {
                return OperateResult.Fail("数据库连接池不存在");
            }
            else
            {
                _libraryManagerService.CreateTable(false, connectionPool);
                return OperateResult.Success("创建数据库表成功");
            }
        }


    }
}
